package newsDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TopicDao {
	// findALL,add,delete,update
	public int add(Topic t) {
		int i = 0;
		String sql = "insert into `topic`(tname)values(?)";
		Connection con = NewsJDBCUtils.getConnection();
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			st = con.prepareStatement(sql);
			st.setString(1, t.getTname());
			i = st.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			NewsJDBCUtils.closeAll(st, rs, con);
		}
		return i;
	}

	public int delete(Topic t) {
		int i = 0;
		String sql = "delete from `topic` where tid=?";
		Connection con = NewsJDBCUtils.getConnection();
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			st = con.prepareStatement(sql);
			st.setLong(1, t.getId());
			i = st.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			NewsJDBCUtils.closeAll(st, rs, con);
		}
		return i;
	}

	public int update(Topic t) {
		String sql = "update `topic` set tname=? where tid=?";
		int i = 0;
		Connection con = NewsJDBCUtils.getConnection();
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			st = con.prepareStatement(sql);
			st.setString(1, t.getTname());
			st.setLong(2, t.getId());
			i = st.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			NewsJDBCUtils.closeAll(st, rs, con);
		}
		return i;
	}

	public List<Topic> findALL() {
		List<Topic> list = new ArrayList<Topic>();
		Topic t = null;
		String sql = "select * from `topic`";
		Connection con = NewsJDBCUtils.getConnection();
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			st = con.prepareStatement(sql);
			rs = st.executeQuery();
			while (rs.next()) {
				t = new Topic();
				t.setId(rs.getInt("tid"));
				t.setTname(rs.getString("tname"));
				list.add(t);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			NewsJDBCUtils.closeAll(st, rs, con);
		}
		return list;
	}
}
